package com.github.bryx.workflowweb.config.intercept;

import cn.hutool.core.util.StrUtil;
import com.github.bryx.workflowweb.config.WorkflowConfigProperties;
import com.github.bryx.workflowweb.config.exception.TokenException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * @author lancer.zyj
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private WorkflowConfigProperties workflowConfigProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod)handler;
            if (method.getBean() instanceof BasicErrorController) {
                throw new TokenException("网络异常，请稍后重试！");
            }
            this.checkToken(request, response, handler);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    private void checkToken(HttpServletRequest request, HttpServletResponse response, Object object) {
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            throw new TokenException("非法访问！");
        }
        if (!Optional.ofNullable(workflowConfigProperties).map(WorkflowConfigProperties::getToken)
                .orElse("").equals(token)) {
            throw new TokenException("非法访问！");
        }
    }

}
